// pages/mes/my-customers-detail/my-customers-detail.js
const app = getApp();
import Toast from '../../../component/toast/toast';
import utils from '../../../utils/util.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        hasMore: true,
        pageSize: 8,
        pageIndex: -1,
        serviceId: 0,
        customerDetail: [],
        worksTime: ['0.5小时', '1小时', '1.5小时', '2小时', '2.5小时', '3小时', '3.5小时','4小时']
    },
    // 事件处理
    bindPickerChange(e) {
        let index = e.currentTarget.dataset.index;
        let workTime = this.data.worksTime[e.detail.value].split('小时')[0] * 60;
        this.startWork(index, workTime);
    },
    selectItem(e) {
        let index = e.currentTarget.dataset.index;
        let obj = this.data.customerDetail[index];
        obj._nickName = obj.Party_A_NickName;
        obj._clientName = app.userInfo.NickName;
        console.log(obj)
        app.globalData.serviceInfo = obj;
        wx.navigateTo({
            url: '/pages/contract/contract?flag=flase',
        })
    },
    confirmClick(e) {
        let that = this;
        let index = e.currentTarget.dataset.index;
        let hintText = '确认接单，即表示你确定承揽该任务，如未按约定完成，将损害你的信誉，请谨慎操作';
        let orderStatus = this.data.customerDetail[index].OrderStatus;
        let isWorking = this.data.customerDetail[index].IsWorking;
        if (orderStatus == 2) {
            hintText = '完成服务，表示你确认已100%完成服务，不可撤销，请谨慎操作'
        }
        wx.showModal({
            title: '提示',
            content: hintText,
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#333',
            confirmText: '确定',
            confirmColor: '#E71015',
            success: function (res) {
                if (res.confirm) {
                    if (orderStatus == 2) {
                        if (isWorking == 0){
                            Toast("请先结束工作，才能完成服务");
                        }else{
                            that.completeOrder(index);
                        }
                    } else if (orderStatus == 1) {
                        that.refundOrder(index, 2);
                    }
                }
            }
        });
    },
    cancelClick(e) {
        let index = e.currentTarget.dataset.index;
        let that = this;
        wx.showModal({
            title: '提示',
            content: '谢绝接单，表示你放弃为该雇主提供本项服务，不可撤销，请谨慎操作',
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#333',
            confirmText: '确定',
            confirmColor: '#E71015',
            success: function (res) {
                if (res.confirm) {
                    that.refundOrder(index, 3);
                }
            }
        })
    },
    clickEndWork(e) {
        let index = e.currentTarget.dataset.index;
        this.endWork(index);
    },
    //网络请求
    startWork(index  , workTime) {
        let that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        wx.request({
            url: app.globalData.serverAddress.startWork,
            data: {
                Id: '',
                OrderId: that.data.customerDetail[index].Id,
                WorkTime: workTime,
                StartWorkTime: utils.formatTime(new Date),
                EndWorkTime: utils.formatTime(new Date)
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function (res) {
                console.log(res.data);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    wx.setStorageSync('work', JSON.stringify(res.data.BodyContent));
                    that.setData({
                        hasMore: true,
                        pageSize: 8,
                        pageIndex: -1,
                        customerDetail: []
                    })
                    that.getCustomerDetail();
                }
                Toast(res.data.Message);
            },
            fail: function (res) { console.log("completeOrder fail：" + JSON.stringify(res)) },
            complete: function (res) { wx.hideLoading(); },
        })
    },
    endWork(index) {
        let that = this;
        let works = JSON.parse(wx.getStorageSync('work'));
        console.log("------>" , works);
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        wx.request({
            url: app.globalData.serverAddress.endWork,
            data: {
                Id: works.Id,
                OrderId: that.data.customerDetail[index].Id,
                WorkTime: 0,
                StartWorkTime: works.StartWorkTime,
                EndWorkTime: utils.formatTime(new Date)
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function (res) {
                console.log(res.data);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    that.setData({
                        hasMore: true,
                        pageSize: 8,
                        pageIndex: -1,
                        customerDetail: []
                    })
                    that.getCustomerDetail();
                }
                Toast(res.data.Message);
            },
            fail: function (res) { console.log("completeOrder fail：" + JSON.stringify(res)) },
            complete: function (res) { wx.hideLoading(); },
        })
    },
    refundOrder(index, orderStatu) {
        let that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        wx.request({
            url: app.globalData.serverAddress.refundOrder,
            data: {
                OrderId: that.data.customerDetail[index].Id,
                CurrentUserInfoId: app.userInfo.Id,
                OrderStatus: orderStatu,
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function (res) {
                console.log(res.data);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    if (orderStatu == 3) {
                        that.data.customerDetail.splice(index, 1);
                        that.setData({
                            customerDetail: that.data.customerDetail
                        });
                    } else if (orderStatu == 2) {
                        let statu = `customerDetail[${index}].OrderStatus`;
                        let statuBo = `customerDetail[${index}].statuBo`;
                        let statuBo1 = `customerDetail[${index}].statuBo1`;
                        let statuText = `customerDetail[${index}].statuText`;
                        let buttonSta = `customerDetail[${index}].statu`;
                        let _statuTxt = '执行中';
                        that.setData({
                            [statu]: 2,
                            [statuBo]: true,
                            [statuBo1]: false,
                            [statuText]: _statuTxt,
                            [buttonSta]: '完成服务'
                        });
                    }

                }
                Toast(res.data.Message);
            },
            fail: function (res) { console.log("completeOrder fail：" + JSON.stringify(res)) },
            complete: function (res) { wx.hideLoading(); },
        })
    },
    completeOrder(index) {
        let that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        wx.request({
            url: app.globalData.serverAddress.completeOrder,
            data: {
                OrderId: that.data.customerDetail[index].Id,
                CurrentUserInfoId: app.userInfo.Id
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            dataType: 'json',
            responseType: 'text',
            success: function (res) {
                console.log(res.data);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    let statu = `customerDetail[${index}].OrderStatus`;
                    let statuBo = `customerDetail[${index}].statuBo`;
                    let statuBo1 = `customerDetail[${index}].statuBo1`;
                    let statuText = `customerDetail[${index}].statuText`;
                    let statuTextColor = `customerDetail[${index}].statuTextColor`;
                    let _statu = 4;
                    let _statuTxt = '待客户确认';
                    that.setData({
                        [statu]: _statu,
                        [statuBo]: false,
                        [statuBo1]: false,
                        [statuText]: _statuTxt,
                        [statuTextColor]: '#009014',
                    });
                }
                Toast(res.data.Message);
            },
            fail: function (res) { console.log("completeOrder fail：" + JSON.stringify(res)) },
            complete: function (res) { wx.hideLoading(); },
        })
    },
    getCustomerDetail() {
        let that = this;
        if (!that.data.hasMore) return;
        let pageI = ++that.data.pageIndex;
        let data = {
            pageSize: that.data.pageSize,
            pageIndex: pageI,
            serviceId: that.data.serviceId
        };
        console.log(JSON.stringify(data));
        that.setData({
            pageIndex: pageI
        });
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        wx.request({
            url: app.globalData.serverAddress.getCustomerDetail,
            data: data,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function (res) {
                console.log(res.data);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    let newList = res.data.BodyContent;
                    newList.forEach(function (item, index) {
                        // console.log(JSON.stringify(item)+"-----"+index);
                        newList[index].statu = "确认接单";
                        newList[index].statuBo = false;
                        newList[index].statuBo1 = false;
                        newList[index].statuTextColor = '#55CAC4';
                        switch (item.OrderStatus) {
                            case 1:
                                newList[index].statuBo = true;
                                newList[index].statuBo1 = true;
                                newList[index].statuText = '待确认';
                                newList[index].statuImg = '../../../assets/icon/icon_is_confirm.png';
                                break;
                            case 2:
                                newList[index].statuBo = true;
                                newList[index].statu = "完成服务";
                                newList[index].statuText = '执行中';
                                newList[index].statuImg = '../../../assets/icon/icon_excuting.png';
                                break;
                            case 4:
                                newList[index].statuText = '待客户确认';
                                newList[index].statuImg = '../../../assets/icon/icon_is_confirm.png';
                                newList[index].statuTextColor = '#009014';
                                break;
                            case 5:
                                newList[index].statuText = '已完成';
                                newList[index].statuImg = '../../../assets/icon/icon_complete.png';
                                break;
                            case 6:
                                newList[index].statuText = '客户申请退款，审核中';
                                newList[index].statuTextColor = '#FF4F53';
                                break;
                            default:
                                newList[index].statuText = '待确认';
                                newList[index].statuImg = '../../../assets/icon/icon_is_confirm.png';
                                break
                        }
                    });
                    let count = res.data.BodyContent.TotalCount;
                    let flag = (that.data.pageIndex + 1) * that.data.pageSize < count;
                    newList = that.data.customerDetail.concat(newList);
                    that.setData({
                        customerDetail: newList,
                        hasMore: flag
                    });
                } else {
                    that.setData({
                        hasMore: false
                    });
                    Toast(res.data.Message);
                }
            },
            fail: function (res) {
                console.log("getCustomerDetail fail:" + JSON.stringify(res))
            },
            complete: function (res) {
                wx.hideLoading();
            },
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            serviceId: options.serviceId
        });
        this.getCustomerDetail();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        this.getCustomerDetail();
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})